import axios from "axios";
//引入element-plus
import { ElMessage } from "element-plus";
//console.log("11", process.env.VUE_APP_API); //undefined??

import router from "@/router";


//创建实例
const service = axios.create({
	baseURL: import.meta.env.VITE_VUE_APP_SERVER_URL, //请求地址
	// withCredentials: true,
	timeout: 60000, //超时
	headers: {
		'Content-Type': 'application/json; charset=utf-8',
		// 'token':sessionStorage.getItem('token')
	}
});

axios.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded";

//添加请求拦截器
service.interceptors.request.use(
	function (config) {
		//在发送请求之前做些什么

		// console.log(config);

		// config.headers.token = sessionStorage.getItem('token');
		config.headers.token = localStorage.getItem('token');

		return config;
	},
	function (error) {
		console.log(error.request);
		const errorData = JSON.parse(error.request.response);
		if (errorData.message) {
			//判断是否具有message属性
			ElMessage({
				message: errorData.message,
				type: "error",
			});
		}
		//对请求错误做些什么
		return Promise.reject(errorData);
	}
);

//添加响  应拦截器
service.interceptors.response.use(
	function (response) {
		//对响应数据做些什么
		//console.log("响应数据", response);
		const data = response.data;
		if (response.status  === 200) {
			return Promise.resolve(data);
		}
		ElMessage({
			message: data.msg,
			type: "error",
		});
		return Promise.reject(data);
	},
	function (error) {
		const errorData = JSON.parse(error.request.response);
		if(error.response.status === 401){
			console.log(error.response.status+"    未登录，跳至登录页面");
			// sessionStorage.setItem('token', '');
			localStorage.setItem('token', '');
			localStorage.setItem('userId', '');
			router.push('/bi_frontend/login');
			return Promise.reject(errorData);
		}
		//对响应错误做些什么
		console.log("error", error.request.response);
		if (errorData.msg) {
			//判断是否具有message属性
			ElMessage({
				message: errorData.msg,
				type: "error",
			});
		}
		return Promise.reject(errorData);
	}
);

//暴露service
export default service;